package com.wenzhoujie;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.umeng.socialize.facebook.controller.utils.ToastUtil;
import com.wenzhoujie.library.title.SDTitleSimple.SDTitleSimpleListener;
import com.wenzhoujie.library.title.SDTitleTwoRightButton.SDTitleTwoRightButtonListener;
import com.wenzhoujie.library.utils.SDResourcesUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.sunday.eventbus.SDBaseEvent;
import com.wenzhoujie.adapter.MerchantDetailAdapter;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.event.EventTagJpush;
import com.wenzhoujie.fragment.MerchantDetailBriefFragment;
import com.wenzhoujie.fragment.MerchantDetailCommentFragment;
import com.wenzhoujie.fragment.MerchantDetailCouponFragment;
import com.wenzhoujie.fragment.MerchantDetailDealsFragment;
import com.wenzhoujie.fragment.MerchantDetailGoodsFragment;
import com.wenzhoujie.fragment.MerchantDetailInfoFragment;
import com.wenzhoujie.fragment.MerchantDetailOtherMerchantFragment;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.IndexActDeal_listModel;
import com.wenzhoujie.model.MerchantdetailClassifyModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.SearchConditionModel;
import com.wenzhoujie.model.ShopGoodsModel;
import com.wenzhoujie.model.act.MerchantitemActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;

/**
 * 门店详情
 * 
 * @author js02
 * 
 */
public class MerchantDetailNewActivity extends BaseActivity {

	/** 商家id */
	public static final String EXTRA_MERCHANT_ID = "extra_merchant_id";

	private MerchantDetailInfoFragment mFragInfo = null;
	private MerchantDetailOtherMerchantFragment mFragOtherSupplier = null;
	private MerchantDetailBriefFragment mFragBrief = null;
	private MerchantDetailDealsFragment mFragDeals = null;
	private MerchantDetailGoodsFragment mFragGoods = null;
	private MerchantDetailCouponFragment mFragCoupon = null;
	private MerchantDetailCommentFragment mFragComment = null;

	private SearchConditionModel mSearcher = new SearchConditionModel();
	private String mStrMerchantId = null;
	private MerchantDetailAdapter adapter = null;
	private PopupWindow pop;
	private List<IndexActDeal_listModel> shop_listModel;
	private List<MerchantdetailClassifyModel> listModel;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setmTitleType(TitleType.TITLE_TWO_RIGHT_BUTTON);
		setContentView(R.layout.act_merchant_detail_new);
		IocUtil.initInjectedView(this);
		init();
	}

	private void init() {
		initIntentData(getIntent());
		initTitle();
		requestMerchantDetail("");
	}

	private void initTitle() {
		mTitleTwoRightBtns.setmListener(new SDTitleTwoRightButtonListener() {

			@Override
			public void onRightButton2CLick_SDTitleTwoRightButton(View v) {

			}

			@Override
			public void onRightButton1CLick_SDTitleTwoRightButton(View v) {
				if (pop.isShowing()) {
					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
					pop.dismiss();
				} else {
					// 显示窗口
					if (listModel!=null) {
						pop.showAsDropDown(v);
					}
					else {
						ToastUtil.showToast(MerchantDetailNewActivity.this, "无分类");
					}
				}
			}

			@Override
			public void onLeftButtonCLick_SDTitleTwoRightButton(View v) {
				finish();
			}
		});
		mTitleTwoRightBtns.setLeftImage(R.drawable.ic_arrow_left_back);
		mTitleTwoRightBtns.setTitleTop(SDResourcesUtil
				.getString(R.string.store_detail));
		mTitleTwoRightBtns.setRightImage1(R.drawable.shop_shoppingclass);
	}

	private void initIntentData(Intent intent) {
		mStrMerchantId = intent.getStringExtra(EXTRA_MERCHANT_ID);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		init();
		super.onNewIntent(intent);
	}

	/**
	 * 加载商家详细信息
	 */
	private void requestMerchantDetail(String dz) {
		if (mStrMerchantId != null) {
			RequestModel model = new RequestModel();
			model.put("act", "merchantitem");
			model.put("act_2", dz);
			model.put("email", mSearcher.getEmail());
			model.put("pwd", mSearcher.getPwd());
			model.put("id", mStrMerchantId);
			model.put("city_id", mSearcher.getCity_id());
			model.put("m_latitude", mSearcher.getM_latitude());
			model.put("m_longitude", mSearcher.getM_longitude());
			RequestCallBack<String> handler = new RequestCallBack<String>() {

				@Override
				public void onStart() {
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					MerchantitemActModel actModel = JsonUtil.json2Object(
							responseInfo.result, MerchantitemActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel)) {
						addFragments(actModel);
					}
				}

				@Override
				public void onFailure(HttpException error, String msg) {

				}

				@Override
				public void onFinish() {
					AppHelper.hideLoadingDialog();
				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		}

	}

	private void addFragments(MerchantitemActModel model) {
		if (model == null) {
			return;
		}

		// 商家信息
		mFragInfo = new MerchantDetailInfoFragment();
		mFragInfo.setmMerchantitemActModel(model);
		replaceFragment(mFragInfo, R.id.act_merchant_detail_new_fl_info);

		// 其他门店
		mFragOtherSupplier = new MerchantDetailOtherMerchantFragment();
		mFragOtherSupplier.setmMerchantitemActModel(model);
		replaceFragment(mFragOtherSupplier,
				R.id.act_merchant_detail_new_fl_other_merchant);

		// 商家介绍
		mFragBrief = new MerchantDetailBriefFragment();
		mFragBrief.setmMerchantitemActModel(model);
		replaceFragment(mFragBrief, R.id.act_merchant_detail_new_fl_brief);

		// 商家其他团购
		mFragDeals = new MerchantDetailDealsFragment();
		mFragDeals.setmMerchantitemActModel(model);
		replaceFragment(mFragDeals, R.id.act_merchant_detail_new_fl_deals);

		// 商家其他商品
		mFragGoods = new MerchantDetailGoodsFragment();
		mFragGoods.setmMerchantitemActModel(model);
		replaceFragment(mFragGoods, R.id.act_merchant_detail_new_fl_goods);
		shop_listModel = new ArrayList<IndexActDeal_listModel>();
		shop_listModel.addAll(model.getGoods_list());

		// 商家的优惠券
		mFragCoupon = new MerchantDetailCouponFragment();
		mFragCoupon.setmMerchantitemActModel(model);
		replaceFragment(mFragCoupon, R.id.act_merchant_detail_new_fl_coupon);

		// 商家评价
		mFragComment = new MerchantDetailCommentFragment();
		mFragComment.setmMerchantitemActModel(model);
		replaceFragment(mFragComment, R.id.act_merchant_detail_new_fl_comment);

		getBizShopCate(model.getSupplier_id());
		
	}

	@Override
	public void onEventMainThread(SDBaseEvent event) {
		super.onEventMainThread(event);
		if (EventTagJpush.EVENT_MERCHANTDETAIL_ID.equals(event
				.getEventTagString())) {
			finish();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (App.getApplication().mRuntimeConfig.isNeedRefreshMerchantDetail()) {
			init();
			App.getApplication().mRuntimeConfig
					.setNeedRefreshMerchantDetail(false);
		}
	}

	private void getBizShopCate(String supplier_id) {

		RequestModel model = new RequestModel();
		model.put("act", "getbizshopcate");
		model.put("supplier_id", supplier_id);
		RequestCallBack<String> handler = new RequestCallBack<String>() {

			@Override
			public void onStart() {

			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				JSONObject json = JSON.parseObject(responseInfo.result);
				Gson gson = new Gson();
				listModel = gson.fromJson(
						json.getString("cate_list"),
						new TypeToken<List<MerchantdetailClassifyModel>>() {
						}.getType());

				// adapter.notifyDataSetChanged();

				LayoutInflater inflater = LayoutInflater
						.from(MerchantDetailNewActivity.this);
				// 引入窗口配置文件
				View view = inflater.inflate(R.layout.merchantdetail_popwindow,
						null);
				// 分类点击
				ListView lv_merchantdetaillistview = (ListView) view
						.findViewById(R.id.lv_merchantdetail_poplistview);
				adapter = new MerchantDetailAdapter(listModel,
						MerchantDetailNewActivity.this);
				lv_merchantdetaillistview.setAdapter(adapter);
				lv_merchantdetaillistview
						.setOnItemClickListener(new myOnItemClickListener(
								listModel));
				// 创建PopupWindow对象
				pop = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
						LayoutParams.WRAP_CONTENT, false);
				// 需要设置一下此参数，点击外边可消失
				pop.setBackgroundDrawable(new BitmapDrawable());
				// 设置点击窗口外边窗口消失
				pop.setOutsideTouchable(true);
				// 设置此参数获得焦点，否则无法点击
				pop.setFocusable(true);
			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}

			@Override
			public void onFinish() {

			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);

	}

	public class myOnItemClickListener implements OnItemClickListener {
		private List<MerchantdetailClassifyModel> listModel;
		private List<IndexActDeal_listModel> listModelto = new ArrayList<IndexActDeal_listModel>();

		public myOnItemClickListener(List<MerchantdetailClassifyModel> listModel) {
			this.listModel = listModel;
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			listModelto.clear();
			int supplier_id = listModel.get(arg2)
					.getId();
			for (int i = 0; i < shop_listModel.size(); i++) {
				if (supplier_id == shop_listModel.get(i).getBiz_shop_cate_id()) {
					listModelto.add(shop_listModel.get(i));
				}

			}
			mFragGoods.setmMerchantitemActModelNotify(listModelto);
			pop.dismiss();
		}

	}
}